package com.zhouz.admin.app.db.service;

import com.zhouz.admin.app.db.domain.SysSystem;
import com.zhouz.admin.app.db.domain.SysSystemExample;
import com.zhouz.admin.app.db.mapper.SysSystemMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LitemallSystemConfigService {
    @Resource
    private SysSystemMapper systemMapper;
    @Cacheable(value = "all",key = "'sysconfig'")
    public Map<String, String> config() {
        SysSystemExample example = new SysSystemExample();
        example.or().andDeletedEqualTo(false);

        List<SysSystem> systemList = systemMapper.selectByExample(example);
        Map<String, String> systemConfigs = new HashMap<>();
        for (SysSystem item : systemList) {
            systemConfigs.put(item.getKeyName(), item.getKeyValue());
        }
        return systemConfigs;
    }

    public  Map<String,List<SysSystem>>  list() {
        SysSystemExample example = new SysSystemExample();
        example.or().andDeletedEqualTo(false);
        List<SysSystem> systemList = systemMapper.selectByExample(example);
        Map<String,List<SysSystem>> list =  systemList.stream().collect(Collectors.groupingBy(SysSystem::getType));
        return list;
    }
    @CacheEvict(value = "all",key = "'sysconfig'")
    public  Map<String, String> updateConfig(Map<String, String> data) {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            SysSystemExample example = new SysSystemExample();
            example.or().andKeyNameEqualTo(entry.getKey()).andDeletedEqualTo(false);

            SysSystem system = new SysSystem();
            system.setKeyName(entry.getKey());
            system.setKeyValue(entry.getValue());
            system.setUpdateTime(LocalDateTime.now());
            systemMapper.updateByExampleSelective(system, example);
        }
        return data;
    }

    public void addConfig(String key, String value) {
        SysSystem system = new SysSystem();
        system.setKeyName(key);
        system.setKeyValue(value);
        system.setAddTime(LocalDateTime.now());
        system.setUpdateTime(LocalDateTime.now());
        systemMapper.insertSelective(system);
    }
}
